package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.query.QueryForObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.PermissionName;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;


@Service
public class PermissionServiceImpl implements IPermissionService {
	@Autowired
	private RequestMappingHandlerMapping rmhm;
	
	@Autowired
	private PermissionMapper permissionMapper;

	@Override
	public void save(Permission entity) {
		permissionMapper.insert(entity);
	}

	@Override
	public void update(Permission entity) {
		permissionMapper.updateByPrimaryKey(entity);
	}

	@Override
	public void delete(Long id) {
		permissionMapper.deleteByPrimaryKey(id);
	}

	@Override
	public Permission get(Long id) {
		return permissionMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<Permission> list() {
		return permissionMapper.selectAll();
	}

	@Override
	public PageResult query(QueryForObject qo) {
		int total=permissionMapper.queryForCount(qo);
		if(total==0){
			return new PageResult();
		}
		List<Permission> rows=permissionMapper.queryForList(qo);
		return new PageResult(total,rows);
	}

	//加载系统权限
	public void reload() {
		//去重复
		List<Permission> list = permissionMapper.selectAll();
		Set<String> set = new HashSet<>();
		for (Permission permission : list) {
			set.add(permission.getResource());
		}
		//获取映射方法集合对象
		Map<RequestMappingInfo, HandlerMethod> handlerMethods = rmhm.getHandlerMethods();
		Collection<HandlerMethod> values = handlerMethods.values();
		//遍历方法对象集合
		RequiresPermissions anno=null;
		Permission permission=null;
		for (HandlerMethod method : values) {
			anno=method.getMethodAnnotation(RequiresPermissions.class);
			if(anno!=null){
				String resource = anno.value()[0];
				if(set.contains(resource)){
					continue;
				}
				String name = method.getMethodAnnotation(PermissionName.class).value();
				permission = new Permission();
				permission.setName(name);
				permission.setResource(resource);
				permissionMapper.insert(permission);
			}
		}
	}

	@Override
	public List<Permission> queryPermissionByRoleId(Long roleId) {
		return permissionMapper.queryPermissionByRoleId(roleId);
	}

	@Override
	public Set<String> queryPermissionResourceByEmpId(Long id) {
		return permissionMapper.queryPermissionResourceByEmpId(id);
	}
}

